//
//  MainViewController.m
//  安好
//
//  Created by 冯凯 on 14-10-21.
//  Copyright (c) 2014年 lianchuangbrother. All rights reserved.
//

#import "MainViewController.h"
#import "BaseNavigation.h"

#import "AnHaoViewController.h"
#import "ConsultViewController.h"
#import "CircleViewController.h"
#import "MoreViewController.h"
#import "LoginViewController.h"
#import "SystemMessageCenter.h"
#import "ForgotViewController.h"
#import "LCStatusBarOverlay.h"
@interface MainViewController (){
    NSArray *backgroud;
    NSArray * seceImage;
    
    UIImageView *redPointImageViewForAnHao;
    UIImageView *redPointImageViewForCircle;
}

@end

@implementation MainViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    NSLog(@"MainViewController");
    
    [self loadViewControllerWithNavigation];
    AppDelegate *app=(AppDelegate *)[[UIApplication sharedApplication] delegate];
    app.logoutDelegate=self;
    self.delegate=self;
    [self setupTabbar];
    [self setupBarItems];
    
    [[NSNotificationCenter defaultCenter] addObserverForName:@"isChangeName" object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *note){
        self.tabBar.hidden = NO;
    }];
    
    [[NSNotificationCenter defaultCenter] addObserverForName:@"PanPush" object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *note){
        NSUserDefaults * user = [NSUserDefaults standardUserDefaults];
        NSString * seleIndex = [user objectForKey:@"selectIndex"];
        if ([seleIndex length] == 0 || [seleIndex isEqualToString:@"0"]) {
            [[NSNotificationCenter defaultCenter] postNotificationName:@"PushAnimation" object:self.anHaoViewController];
        }else if ([seleIndex isEqualToString:@"1"]){
            [[NSNotificationCenter defaultCenter] postNotificationName:@"PushAnimation" object:self.consultViewController];
        }else if ([seleIndex isEqualToString:@"2"]){
            [[NSNotificationCenter defaultCenter] postNotificationName:@"PushAnimation" object:self.circleViewController];
        }else{
            [[NSNotificationCenter defaultCenter] postNotificationName:@"PushAnimation" object:self.moreViewController];

        }

    }];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(doShowRedPointForAnHao) name:kDidGetAndStoreSystemNotification object:nil];
    [self doShowRedPointForAnHao];//第一次进界面时，判断红点，以后都是通过通知来更新

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(doShowRedPointForCircle) name:kDidGetAndStoreNoticeNotification object:nil];
    [self doShowRedPointForCircle];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(doShowRedPointForAnHao) name:kDidGetAndStoreNewsNotification object:nil];
    
}

- (void)doShowRedPointForAnHao{
    if ([[SystemMessageCenter instance] isHaveNoReadedMessageForAll]) {//有没读的
        dispatch_async(dispatch_get_main_queue(), ^{
            redPointImageViewForAnHao.hidden = NO;
        });
    }
    else{
        dispatch_async(dispatch_get_main_queue(), ^{
            redPointImageViewForAnHao.hidden = YES;
        });
    }
}

- (void)doShowRedPointForCircle{
    if ([[[SystemMessageCenter instance] selectAllNoReadedSecretaryNoticeMessage] count] > 0) {//有没读的
        dispatch_async(dispatch_get_main_queue(), ^{
            redPointImageViewForCircle.hidden = NO;
        });
    }
    else{
        dispatch_async(dispatch_get_main_queue(), ^{
            redPointImageViewForCircle.hidden = YES;
        });
    }
}

- (void)setupTabbar {
    self.tabBar.backgroundImage = [self imageWithColor:[ClassMethodsViewController colorWithHexString:TABBAR_BACKGROUNDCOLOR_16]];
}

- (void)setupBarItems {
    NSArray *normalImageNames = @[@"底部_安好",@"底部_咨询",@"底部_圈子",@"底部_发现"];
    NSArray *selectedImageNames = @[@"底部_安好Hight",@"底部_咨询Hight",@"底部_圈子Hight",@"底部_发现Hight"];
    for (NSInteger i = 0; i < self.viewControllers.count; i++) {
        UINavigationController *navController = [self.viewControllers objectAtIndex:i];
        [navController.tabBarItem setImage:[[UIImage imageNamed:normalImageNames[i]] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];
        [navController.tabBarItem setSelectedImage:[[UIImage imageNamed:selectedImageNames[i]]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];
        navController.tabBarItem.imageInsets = UIEdgeInsetsMake(5, 0, -5, 0);
        if (i == 0) {
            NSInteger min_X = 0;
            for (NSInteger i=1; i<=3; i++) {
                if (((UIView *)[navController.tabBarController.tabBar.subviews objectAtIndex:min_X]).frame.origin.x > ((UIView *)[navController.tabBarController.tabBar.subviews objectAtIndex:i]).frame.origin.x) {
                    min_X = i;
                }
            }
            CGFloat x = ((UIView *)[navController.tabBarController.tabBar.subviews objectAtIndex:min_X]).frame.origin.x + ((UIView *)[navController.tabBarController.tabBar.subviews objectAtIndex:min_X]).frame.size.width*2/3;
            
            redPointImageViewForAnHao = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"point2"]];
            redPointImageViewForAnHao.frame = CGRectMake(x, 0, 10, 12);
            redPointImageViewForAnHao.hidden = YES;
            [navController.tabBarController.tabBar addSubview:redPointImageViewForAnHao];
            
//            NSLog(@"----%@   x=%f",navController.tabBarController.tabBar.subviews,x);
        }
        if (i == 2) {
            CGFloat x = ((UIView *)[navController.tabBarController.tabBar.subviews objectAtIndex:4]).frame.origin.x + ((UIView *)[navController.tabBarController.tabBar.subviews objectAtIndex:4]).frame.size.width*2/3;
            
            redPointImageViewForCircle = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"point2"]];
            redPointImageViewForCircle.frame = CGRectMake(x, 0, 10, 12);
            redPointImageViewForCircle.hidden = YES;
            [navController.tabBarController.tabBar addSubview:redPointImageViewForCircle];
            
//            NSLog(@"----%@   x=%f",navController.tabBarController.tabBar.subviews,x);
        }
    }
    
}
- (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController
{
    if ([[[(BaseNavigation *)viewController viewControllers] objectAtIndex:0] isKindOfClass:[ConsultViewController class]]) {
        UserModel * userModel = [[UserManager shareInstance]getUserInfo];
        NSString * name= userModel.username;
        NSUserDefaults *userdefault=[NSUserDefaults standardUserDefaults];
        NSString *mobile_certification=[NSString stringWithFormat:@"%@",[userdefault valueForKey:@"authentication"]];
        if (name.length>0&&[mobile_certification isEqualToString:@"1"]) {
            [super setSelectedViewController:viewController];
            NSString * selectIndex = [NSString stringWithFormat:@"%lu",(unsigned long)self.selectedIndex];
            NSUserDefaults * user = [NSUserDefaults standardUserDefaults];
            [user setObject:selectIndex forKey:@"selectIndex"];
            return YES;
        }
        else if (name.length>0&&[mobile_certification isEqualToString:@"0"])
        {
            LoginViewController * loginViewController = [[LoginViewController alloc]initWithNibName:@"LoginViewController" bundle:nil];
            [self presentViewController:loginViewController animated:YES completion:^{
            }];
            loginViewController.realName.isFromRegist=NO;
            [loginViewController showRealNameView];
            return NO;
        }
        else
        {
            [[[( BaseNavigation*)viewController viewControllers] objectAtIndex:0] isLogin];
            return NO;
        }
    }else
    {
        [super setSelectedViewController:viewController];
        NSString * selectIndex = [NSString stringWithFormat:@"%lu",(unsigned long)self.selectedIndex];
        NSUserDefaults * user = [NSUserDefaults standardUserDefaults];
        [user setObject:selectIndex forKey:@"selectIndex"];
        return YES;
    }
    MyNSLog("%lu",(unsigned long)self.selectedIndex);
}
- (void)loadViewControllerWithNavigation
{
    self.anHaoViewController = [[AnHaoViewController alloc]initWithNibName:@"AnHaoViewController" bundle:nil];
    self.consultViewController = [[ConsultViewController alloc]initWithNibName:@"ConsultViewController" bundle:nil];
    self.circleViewController = [[CircleViewController alloc]initWithNibName:@"CircleViewController" bundle:nil];
    self.moreViewController = [[MoreViewController alloc]init];
    NSMutableArray *navs = [NSMutableArray arrayWithCapacity:4];
    NSArray *viewControllers = [NSArray arrayWithObjects:self.anHaoViewController,self.consultViewController,self.circleViewController,self.moreViewController, nil];
    for (id viewController in viewControllers) {
        self.navigtaion = [[BaseNavigation alloc] initWithRootViewController:viewController];
        self.navigtaion.delegate = self;
        [navs addObject:self.navigtaion];
    }
    self.viewControllers = navs;
}
- (void)navigationController:(UINavigationController *)navigationController didShowViewController:(UIViewController *)viewController animated:(BOOL)animated
{
    if (navigationController.viewControllers.count == 1) {
        
        [[NSNotificationCenter defaultCenter] postNotificationName:@"StarLetfPan" object:nil];

    }else if (navigationController.viewControllers.count >= 2){
        [[NSNotificationCenter defaultCenter] postNotificationName:@"StopLetfPan" object:nil];
        self.tabBar.hidden = YES;

    }
}
- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated
{
    if (navigationController.viewControllers.count == 1) {
        self.tabBar.hidden = NO;

    }
}
- (UIImage *)imageWithColor:(UIColor *)color
{
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma  mark logoutDelegate
- (void)logoutAndskiptoMain:(NSString *)index
{
    
    if (self.tabBarController.selectedIndex!=0) {
        [self setSelectedIndex:0];
    }else
    {
        [[self.viewControllers objectAtIndex:0] popToRootViewControllerAnimated:NO];
        [self setSelectedIndex:0];
    }

    if ([index isEqualToString:@"0"]) {
        AnHaoViewController *anhao=(AnHaoViewController *)[[[self.viewControllers objectAtIndex:0] viewControllers]objectAtIndex:0];
        [anhao refreshNewInfo];
        ForgotViewController *forgot=[[ForgotViewController alloc]initWithNibName:@"ForgotViewController" bundle:nil];
        forgot.isLogout=YES;
        [anhao.navigationController pushViewController:forgot animated:YES];
    }
    else
    {
        AnHaoViewController *anhao=(AnHaoViewController *)[[[self.viewControllers objectAtIndex:0] viewControllers]objectAtIndex:0];
        [anhao refreshNewInfo];
    }
    LCStatusBarOverlay *statusbar=[LCStatusBarOverlay shared];
    [statusbar hidenMessageLabel];
    AppDelegate *app=(AppDelegate *)[[UIApplication sharedApplication]delegate];
    [app.heartBeatTimer invalidate];
    app.heartBeatTimer=nil;
    app.webSocket=nil;
    app.webSocket.delegate=nil;

    [[NSNotificationCenter defaultCenter] postNotificationName:kDidGetAndStoreSystemNotification object:nil];
    [self doShowRedPointForCircle];
    [[NSNotificationCenter defaultCenter] postNotificationName:kDidGetAndStoreNewsNotification object:nil];
//    [[NSNotificationCenter defaultCenter] postNotificationName:kDidGetAndStoreNoticeNotification object:nil userInfo:nil];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
